##Make ts plot
library(lubridate)
library(MASS)
library(xlsx)
library(dplyr)
library(ggplot2)
library(splines)

dataFile <- "all_polls_IEBC2.xlsx"

tsfil <- read.xlsx(dataFile, sheetIndex = 1, header=TRUE, colClasses = "character")
tsfil$START_DATE <- as.POSIXct(tsfil$START_DATE, tz = "UTC")
tsfil$END_DATE <- as.POSIXct(tsfil$END_DATE, tz= "UTC")
tsfil$INTERVAL <- new_interval(tsfil$START_DATE, tsfil$END_DATE, tzone = "UTC")


tsVal <- filter(tsfil, !is.na(pctNotAtAll))

paste0("The plot will have ", nrow(tsVal), " points")
plotBegin <- mdy("6/1/2002")
plotEnd <- mdy("1/1/2016")

#commission dates
eckEnd <- mdy("10/1/2008")
iebcBegin <- mdy("5/7/2009")
iebcEnd <- mdy("10/8/2011")
iiecBegin <- mdy("10/8/2011")

#election dates
election1 <- mdy("12/27/2002")
election2 <- mdy("12/27/2007")
election3 <- mdy("3/4/2013")

ggplot(tsVal, aes(x=START_DATE, y=pctNotAtAll)) +
  #stat_smooth(se=FALSE, method ="loess") +
              #, formula = y~ns(x, knots =c(election1, election2, election3))) +
  geom_point(size = 3, aes(shape=firm)) +
  scale_shape_manual(values=c(seq(0,4), 8, 7)) +
  scale_y_continuous(breaks = seq(0,60,10), limits = c(0,65), expand = c(0, 0)) +
  ylab(label = "Percent with no confidence/trust (higher is worse)") +
  xlab("Date") +
  xlim(plotBegin, plotEnd) +
  geom_segment(aes(x = plotBegin, y = 59, xend = eckEnd, yend = 59), 
               arrow=arrow(ends="first"), colour = "black", linetype = 2, inherit.aes = FALSE) +
  annotate("text", x = mdy("6/1/2005"), y = 61,label="ECK") +
  geom_segment(aes(x = iebcBegin, y = 57, xend = iebcEnd, yend = 57), 
               colour = "black", linetype = 2, inherit.aes = FALSE) +
  annotate("text", x = mdy("6/1/2010"), y = 59,label="IIEC") +
  geom_segment(aes(x = iiecBegin, y = 55, xend = plotEnd, yend = 55),
               arrow= arrow(ends="last"), colour = "black", linetype = 2, inherit.aes = FALSE) +
  annotate("text", x = mdy("9/1/2013"), y = 57,label="IEBC") +
  geom_segment(aes(x = election1, y = 0, xend = election1, yend = 55),
               colour = "grey50", linetype = 33, lwd = 1.2, inherit.aes = FALSE) +
  geom_segment(aes(x = election2, y = 0, xend = election2, yend = 55),
               colour = "grey50", linetype = 33, lwd =1.2, inherit.aes = FALSE) +
  geom_segment(aes(x = election3, y = 0, xend = election3, yend = 55),
               alpha = .40, colour = "grey50", linetype = 33, lwd =1.2, inherit.aes = FALSE) + 
  theme_bw() +
  theme(legend.title=element_blank())
ggsave(file="tsPlotvRR.tif", device = "tiff", width = 10 , height = 7, dpi = 800)
ggsave(file="tsPlotvRR.pdf", width = 10 , height = 7)
